// pages/departAdd/departAdd.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../utils/util');
import Base64 from '../../utils/Base64.js';
import { relativeTimeThreshold } from '../../libs/moment.min.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,
    //省市区相关
    showProvince:false,
    provinceId:null,
    provinceName:'',
    provinceObj:null,
    showCity:false,
    cityId:null,
    cityName:'',
    cityObj:null,
    showDistrict:false,
    districtId:null,
    districtName:'',
    districtObj:null,
    valueSearchProvince:'',
    valueSearchCity:'',
    valueSearchDistrict:'',
    //父级选择框
    showFather:false,
    //父级选择数据
    fatherList:[],
    //搜索父级
    valueSearchFather:'',
    //大区选择框
    showRegion:false,
    //大区选择数据
    regionList:[],
    //搜索大区
    valueSearchRegion:'',
    //保洁供应方选择框
    showClean:false,
    //保洁供应方选择数据
    cleanList:[],
    //搜索保洁供应方
    valueSearchClean:'',
    //当前用户
    user:{},
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,

    //人员选择框
    showUser: false,
    //人员列表
    userList: [],
    //人员搜索关键词
    searchValue: '',
    //物业工单人员搜索关键词
    searchCleanOrderValue:'',
    //已选人员列表
    listMap: {},
    //已选保洁工单接收人列表
    listCleanOrderMap: {},
    //全选
    checkedAll: false,
    //间隔时间
    showHealth: false,
    showPositioning: false,
    showTaskApprove:false,
    taskApproveList:[],
    //已选择任务审批人
    listTaskApproverMap:{},
    currentLevel:1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;

    this.setData({
      user: user,
      code: Base64.encode(new Date() + user.userName),
      //在这里给map赋值，避免后面操作时set方法不可用
      listMap: new Map(),
      listCleanOrderMap: new Map(),
      listTaskApproverMap:new Map()
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('项目传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit:true,
          currentLevel:paramObj.level
        })
        //获取修改的数据
        this.getInfo();
      }else{
        this.setData({
          editInfo: paramObj
        })
      }
    }

    //默认勾选物业项目
    let isProject='editInfo.isProject';
    this.setData({
      [isProject]: true
    })
  },

  //提交表单##
  onConfirmAdd(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let user=app.globalData.userInfo;
    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;
    let flag=true;



    //项目名称必填
    let name=obj.name.trim();
    if(!this.formNotEmpty(name,'nameMessage','请输入项目名称')){
      return;
    }

    if(td.isEdit && editInfo.name==name){
    }else{
      //项目名是否重复
      flag=this.isExist(name).then(value => {
        if(value){
          this.setData({
            nameMessage: '此项目已存在',
            disabled: true
          })
        }
        return !value;
      });
    }

    //上级部门必填
    console.log(this.data.currentLevel);
    console.log(!editInfo.fid&&this.data.currentLevel!=1);
    if(!editInfo.fid&&this.data.currentLevel!=1){
      Toast.fail('请选择上级部门');
      return;
    }

    //省市区必填
    if(td.provinceObj && td.cityObj && td.districtObj){
    }else{
      Toast.fail('省市区未填写完整');
      return;
    }
  
    //活跃度脱岗时间间隔
    // let offMessageInterval=obj.offMessageInterval.trim();
    // if(offMessageInterval){
    //   if(offMessageInterval>=30){
    //   }else{
    //     Toast.fail('请输入大于30的数字');
    //     return;
    //   }
    // }

    //权限
    let authArrs=[user.depart, user.departObj[0].companyId, td.id, editInfo.companyId, editInfo.fid, editInfo.regionId];
    let authArr=[];
    authArrs.forEach(item => {
      if(item){
        authArr.push(item);
      }
    });
    let authSet=new Set(authArr);
    authArr=Array.from(authSet);

    //字段
    let param={
      className:'depart',
      data:{
        requestToken: td.code,
        id: td.id,
        //项目名称
        name: name,
        //简称
        nickName: obj.nickName.trim(),
        //地区
        area:{
          province: td.provinceObj,
          city: td.cityObj,
          district: td.districtObj,
        },
        //地址
        addressDetail: obj.addressDetail.trim(),
        //顶级部门
        companyId: editInfo.companyId,
        //合伙人
        partnerId: editInfo.partnerId,
        //上级部门
        fid: editInfo.fid,
        //后台结构树级别
        level: editInfo.level,
        //数据权限
        dataAuthority: {
          depart: authArr
        },
        //大区id
        rid: editInfo.rid,
        //大区id
        regionId: editInfo.regionId,
        //是否物业项目
        isProject: editInfo.isProject,
        //是否大区
        isRegion: editInfo.isRegion,
        //是否是保洁供应方
        isCleaningSupplier: editInfo.isCleaningSupplier,
        //保洁供应方
        cleaningSupplier: editInfo.cleaningSupplier,
        //活跃度脱岗时间间隔
        // : offMessageInterval ? parseInt(offMessageInterval) : null
        healthReportInterval:obj.healthReportInterval,
        positioningReportInterval:obj.positioningReportInterval,
        positioning:obj.positioning,
        health:obj.health
      }
    }

    //保洁负责人（保洁工单功能用到）
    if(editInfo.cleanOrderUsers && editInfo.cleanOrderUsers.length){
      param.data.cleanOrderUsers=editInfo.cleanOrderUsers
    }else{
      //加个else，如果修改时把这项清空了，那保存数据也得清空
      param.data.cleanOrderUsers=null;
    }

    //活跃度围栏脱岗提醒人员
    if(editInfo.offMessageUsers && editInfo.offMessageUsers.length){
      param.data.offMessageUsers = editInfo.offMessageUsers;
    }else{
      param.data.offMessageUsers=null;
    }
    //任务审批人
    if(editInfo.taskApproveList && editInfo.taskApproveList.length){
      param.data.taskApproveList = editInfo.taskApproveList;
    }else{
      param.data.taskApproveList=null;
    }
    

    //只限添加时
    if(!td.isEdit){
      //创建人
      param.data.createUser=app.globalData.userInfo;
      //类型，只能客户
      param.data.type=4;
      //后台树用到的
      param.data.hasChildren=false;
      //后台树用到的？
      param.data.count=0;
    }

    console.log(param);

    Promise.all([flag]).then(value => {
      let passed=value.every(val=>{
        return val;
      });
      if(passed){
        // console.log('~添加项目~');
        // console.log(param.data);
        // return;

        //避免表单重复提交
        Toast.loading({
          duration: 0,
          forbidClick: true,
          message: '数据提交中...'
        });

        CommonService.goSave(param).then(res=>{
          if (res.statusCode == 200 && res.data.success == true){
            Toast.success('成功');
            this.setData({
              disabled:false
            })

            //更新上级部门
            this.updateFather(editInfo.fid);

            //关联查询字段更新到设备表
            this.updateEquipment(res.data.data);

            //将提醒相关信息保存到工牌表
            if(td.isEdit){
              let obj2={
                offMessageUsers: param.data.offMessageUsers,
               // offMessageInterval: param.data.offMessageInterval,
                depart: res.data.data.id
              }
              this.updateCardReceiver(obj2);
            }

            //发送指令

            setTimeout(() => {
              //返回操作
              this.backAndRefresh();
            }, 1000);

          }else if(res.statusCode==202){
            Toast.fail('您操作太快了,请勿重复提交');
          }
        }).catch((error) => {
          Toast.clear();
        })
      }
    });
  },

  //获取项目信息
  getInfo(){
    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        id:this.data.id,
        selectFields: ['id','name','nickName','addressDetail','area','companyId','partnerId','fid','level','rid',
        'regionId','isProject','isRegion','isCleaningSupplier','cleaningSupplier','cleanLeader','offMessageUsers',
        'offMessageInterval','cleanOrderUsers','taskApproveList']
      },
      
    }
    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        //查询父级名称
        if(result.fid){
          this.getDepartName(result.fid).then(value => {
            if(value){
              let fatherName='editInfo.fatherName';
              this.setData({
                [fatherName]:value
              })
            }
          });
        }

        //查询大区名称
        if(result.rid){
          this.getDepartName(result.rid).then(value => {
            if(value){
              let regionName='editInfo.regionName';
              this.setData({
                [regionName]:value
              })
            }
          });
        }

        //查询保洁供应方名称
        if(!result.isCleaningSupplier && result.cleaningSupplier && result.cleaningSupplier.length){
          this.getDepartName(result.cleaningSupplier[0]).then(value => {
            if(value){
              let cleanName='editInfo.cleanName';
              this.setData({
                [cleanName]:value
              })
            }
          });
        }

        //活跃度围栏脱岗提醒显示的名字
        if(result.offMessageUsers && result.offMessageUsers.length){
          let names=[];
          let map=new Map();
          result.offMessageUsers.forEach(item => {
            names.push(item.nickName);
            map.set(item.userId,item);
          });
          result.self_offMessageUsers=names;
          this.setData({
            editInfo: result
          })

          this.setData({
            listMap: map,
            userList: userList,
          })
        };


        if(result.taskApproveList && result.taskApproveList.length){
          let names=[];
          let map=new Map();
          result.taskApproveList.forEach(item => {
            names.push(item.nickName);
            map.set(item.userId,item);
          });
          result.self_taskApprover=names;
          this.setData({
            editInfo: result
          })

          //复选框选中状态
          let userList=this.data.userList;
          userList.forEach(item => {
            if(map.get(item.id)){
              item.checked=true;
            }
          });

          this.setData({
            listMap: map,
            userList: userList,
          })
        };


        let names =[]
        if(result.cleanOrderUsers){
          result.cleanOrderUsers.forEach(item => {
            names.push(item.name);
          });
          result.self_cleanOrderUsers=names;
        }
       

        console.log('修改项目信息回显');
        console.log(result);

        this.setData({
          editInfo: result,
          taskApproveList:result.taskApproveList
        })

        //编辑设备时获取各个字段的值
        this.getInputValue();
      }
    }).catch((error) => {
    })
  },

  //编辑设备时获取各个字段的值
  getInputValue(){
    let info=this.data.editInfo;

    this.setData({
      provinceName:info.area.province.name,
      cityName:info.area.city.name,
      districtName:info.area.district.name,
      provinceObj:info.area.province,
      provinceId:info.area.province.id,
      cityObj:info.area.city,
      cityId:info.area.city.id,
      districtObj:info.area.district,
      districtId:info.area.district.id
    })
  },

  //返回操作
  backAndRefresh(){
    //获取列表页对象
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    if(prevPage.route=='pages/equipmentAdd/equipmentAdd'){
      //添加设备-查询项目
      prevPage.getProjectData();
    }

    if(prevPage.route=='pages/departList/departList'){
      //刷新列表页数据
      prevPage.refreshListAndPage();
    }

    //返回上一页
    wx.navigateBack();
  },

  //判断表单非空（涉及到数据提交，field可以在调用前去空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //显示省
  onShowProvince(){
    this.setData({
			showProvince: true
    })
    //查询省
    this.findProvince();
  },

  //查询省
  findProvince(){
    let param = {
      isAuth: false,
      className: 'city',
      data: {
        searchAll: true,
        level:'1',
        selectFields: ['id','name']
      }
    }

    //名称模糊查询
    if(this.data.valueSearchProvince){
      param.data.name='%'+this.data.valueSearchProvince+'%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          provinceList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏省
  onCloseProvince(){
    this.setData({
			showProvince: false
    })
  },

  //确认省
  onConfirmProvince(e){
    this.setData({
      provinceId: e.detail.value.id,
      provinceName: e.detail.value.text,
      provinceObj:e.detail.value.obj,

      cityId:null,
      cityName:'',
      cityObj:null,

      districtId:null,
      districtName:'',
      districtObj:null,

      valueSearchProvince:'',
      disabled: false
    });

    this.onCloseProvince();
  },

  //显示城市
  onShowCity(){
    this.setData({
			showCity: true
    })
    //查询城市
    this.findCity();
  },

  //查询城市
  findCity(){
    let param = {
      isAuth: false,
      className: 'city',
      data: {
        searchAll: true,
        level:'2',
        fid:this.data.provinceId,
        selectFields: ['id','name']
      }
    }

    //名称模糊查询
    if(this.data.valueSearchCity){
      param.data.name='%'+this.data.valueSearchCity+'%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          cityList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏城市
  onCloseCity(){
    this.setData({
			showCity: false
    })
  },

  //确认城市
  onConfirmCity(e){
    this.setData({
      cityId: e.detail.value.id,
      cityName: e.detail.value.text,
      cityObj:e.detail.value.obj,

      districtId:null,
      districtName:'',
      districtObj:null,

      valueSearchCity:'',
      disabled: false
    });

    this.onCloseCity();
  },

  //显示区
  onShowDistrict(){
    this.setData({
			showDistrict: true
    })
    //查询区
    this.findDistrict();
  },

  //查询区
  findDistrict(){
    let param = {
      isAuth: false,
      className: 'city',
      data: {
        searchAll: true,
        level:'3',
        fid:this.data.cityId,
        selectFields: ['id','name']
      }
    }

    //名称模糊查询
    if(this.data.valueSearchDistrict){
      param.data.name='%'+this.data.valueSearchDistrict+'%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          districtList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏区
  onCloseDistrict(){
    this.setData({
			showDistrict: false
    })
  },

  //确认区
  onConfirmDistrict(e){
    this.setData({
      districtId: e.detail.value.id,
      districtName: e.detail.value.text,
      districtObj:e.detail.value.obj,
      valueSearchDistrict:'',
      disabled: false
    });

    this.onCloseDistrict();
  },

  //更新上级部门
  updateFather(id){
    let param = {
      className: 'depart',
      data: {
        filter: {
          id:id
        },
        update: {
          set: {
            hasChildren:true
          }
        }
      }
    }

    CommonService.goUpdate(param).then(res => {
    }).catch((error) => {
    })
  },

  //选择省-搜索
  onChangeProvince(e){
    this.setData({
      valueSearchProvince: e.detail
    })
    //查询
    this.findProvince();
  },

  //选择市-搜索
  onChangeCity(e){
    this.setData({
      valueSearchCity: e.detail
    })
    //查询
    this.findCity();
  },

  //选择区-搜索
  onChangeDistrict(e){
    this.setData({
      valueSearchDistrict: e.detail
    })
    //查询
    this.findDistrict();
  },

  //关联查询字段更新到设备表
  updateEquipment(obj){
    let param={
      departId:obj.id
    }
    CommonService.updateEquipmentAll(param).then(res=>{
    }).catch((error) => {
    })
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //显示父级
  onShowFather(){
    this.setData({
			showFather: true
    })
    this.getFatherList();
  },

  //查询父级
  getFatherList(){
    this.setData({
      fatherList: []
    })

    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        // complex:[{
        //     or:{
        //         "companyId":this.data.editInfo.companyId,
        //         "fid":this.data.editInfo.companyId
        //     }
        // }],
        searchAll: true,
        selectFields: ['id','name','companyId','partnerId','fid','level']
      }
    }

    //模糊查询
    if(this.data.valueSearchFather){
      param.data.name='%' + this.data.valueSearchFather + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          fatherList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏父级
  onCloseFather(){
    this.setData({
      showFather: false,
      valueSearchFather:''
    })
  },

  //确认父级
  onConfirmFather(e){
    let companyId='editInfo.companyId';
    let partnerId='editInfo.partnerId';
    let fid='editInfo.fid';
    let fatherName='editInfo.fatherName';
    let level='editInfo.level';

    let obj=e.detail.value.obj;

    this.setData({
      [companyId]: obj.companyId,
      [partnerId]: obj.partnerId,
      [fid]: obj.id,
      [fatherName]: obj.name,
      [level]: obj.level+1,
      disabled: false
    })
    this.onCloseFather();
  },

  //搜索父级
  onChangeFatherVal(e){
    this.setData({
      valueSearchFather: e.detail
    })
    this.getFatherList();
  },

  //根据id查询名称
  getDepartName(id){
    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        id: id,
        selectFields: ['name'],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }
    console.log("查询腹肌");
    console.log(param);
    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.result.length) {
          resolve(res.data.data.result[0].name);
        } else {
          resolve(null);
        }
      }).catch((error) => {
        resolve(null);
      })
    });
  },

  //显示大区
  onShowRegion(){
    this.setData({
			showRegion: true
    })
    this.getRegionList();
  },

  //查询大区
  getRegionList(){
    this.setData({
      regionList: []
    })

    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        companyId:this.data.editInfo.companyId,
        searchAll: true,
        isRegion: true,
        selectFields: ['id','name']
      }
    }

    if(this.data.valueSearchRegion){
      param.data.name='%' + this.data.valueSearchRegion + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          regionList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏大区
  onCloseRegion(){
    this.setData({
      showRegion: false,
      valueSearchRegion:''
    })
  },

  //确认大区
  onConfirmRegion(e){
    let rid='editInfo.rid';
    let regionId='editInfo.regionId';
    let regionName='editInfo.regionName';

    this.setData({
      [rid]: e.detail.value.id,
      [regionId]: e.detail.value.id,
      [regionName]: e.detail.value.text,
      disabled: false
    })

    this.onCloseRegion();
  },

  //搜索大区
  onChangeRegionVal(e){
    this.setData({
      valueSearchRegion: e.detail
    })
    this.getRegionList();
  },

  //清除大区选择
  onCancelRegion(){
    let rid='editInfo.rid';
    let regionName='editInfo.regionName';

    this.setData({
      [rid]:null,
      [regionName]:''
    })

    this.onCloseRegion();
  },

  //是否物业项目
  onChangeIsProject(event) {
    let isProject='editInfo.isProject';
    this.setData({
      [isProject]: event.detail
    })
  },

  //是否大区
  onChangeIsRegion(event) {
    let isRegion='editInfo.isRegion';
    this.setData({
      [isRegion]: event.detail,
    })
  },

  //是否保洁供应方
  onChangeCleaning(event) {
    let isCleaningSupplier='editInfo.isCleaningSupplier';
    this.setData({
      [isCleaningSupplier]: event.detail,
    })
  },

  //显示保洁供应方
  onShowClean(){
    this.setData({
			showClean: true
    })
    this.getCleanList();
  },

  //查询保洁供应方
  getCleanList(){
    this.setData({
      cleanList: []
    })

    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        searchAll:true,
        type:4,
        level:1,
        selectFields:["id","name"]
      }
    }

    if(this.data.valueSearchClean){
      param.data.name='%' + this.data.valueSearchClean + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          cleanList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏保洁供应方
  onCloseClean(){
    this.setData({
      showClean: false,
      valueSearchClean:''
    })
  },

  //确认保洁供应方
  onConfirmClean(e){
    let cleaningSupplier='editInfo.cleaningSupplier';
    let cleanName='editInfo.cleanName';

    this.setData({
      [cleaningSupplier]: [e.detail.value.id],
      [cleanName]: e.detail.value.text,
      disabled: false
    })
    this.onCloseClean();
  },

  //搜索保洁供应方
  onChangeCleanVal(e){
    this.setData({
      valueSearchClean: e.detail
    })
    this.getCleanList();
  },

  //清除保洁供应方选择
  onCancelClean(){
    let cleaningSupplier='editInfo.cleaningSupplier';
    let cleanName='editInfo.cleanName';

    this.setData({
      [cleaningSupplier]:null,
      [cleanName]:''
    })

    this.onCloseClean();
  },

  //项目名是否重复
  isExist(name){
    let param={
      isAuth:false,
      className:'depart',
      data:{
        name:name,
        companyId: this.data.editInfo.companyId,
        nbl:Base64.encode(util.timeFormatDay(new Date())),
        selectFields:["id"]
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.result.length) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //保洁负责人
    if(field=='cleanLeader'){
      this.setData({
        selectTitle: '保洁负责人',
        showSelectSearch: true
      })
      this.getUserList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //保洁负责人
    if(selectField=='cleanLeader'){
      //人员是否绑定微信
      let flag=false;
      flag=this.isBindWeixin(e.detail.value.id).then(value => {
        if(!value){
          Toast.fail({
            duration: 3000,
            message: '该人员未绑定微信（个人中心-设置-绑定微信）'
          });
        }
        return value;
      });

      Promise.all([flag]).then(value => {
        let passed=value.every(val=>{
          return val;
        });
        if(passed){
          obj='editInfo.cleanLeader';
          this.setData({
            [obj]: e.detail.value.obj
          })
        }else{
          return;
        }
      });
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //保洁负责人
    if(selectField=='cleanLeader'){
      obj='editInfo.cleanLeader';
    }

    if(id && name){
      this.setData({
        [id]:null,
        [name]:''
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //保洁负责人
    if(selectField=='cleanLeader'){
      this.getUserList();
    }
  },

  //查询人员
  getUserList(){
    let param = {
     // isAuth: true,
      className: 'user',
      data: {
       // depart: this.data.paramObj.companyId,
        searchAll: true,
        selectFields: ['id','userName','personalPhone','nickName']
      }
    }

    if(this.data.valueSearch){
      param.data.userName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            name: item.nickName,
            id: item.id
          });
        });

        if(this.data.editInfo && this.data.editInfo.cleanOrderUsers){
          console.log("进来了");
          console.log(this.data.editInfo);
          let map=new Map();
          this.data.editInfo.cleanOrderUsers.forEach(item => {
            map.set(item.id,item);
          });
          //复选框选中状态
          let userList=arr;
          userList.forEach(item => {
            if(map.get(item.id)){
              console.log(item);
              item.checked=true;
            }
          });
          console.log("userList");
          console.log(userList);

          this.setData({
            listCleanOrderMap: map,
            selectList: userList
          })
        };
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //验证人员是否绑定微信
  isBindWeixin(id){
    let param={
      isAuth: false,
      className:'wechatLogin',
      data:{
        userId: id,
        selectFields: ['id'],
        nbl:Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.result.length) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //显示任务审批人
  onTaskApprove(){
    this.setData({
      showTaskApprove: true
    })
    //查询人员
    this.findPerosnnel();
  },

  //查询人员
  findPerosnnel(){
    const {paramObj} = this.data
    console.log("paramObj");
    console.log(paramObj);
    this.setData({
      taskApproveList:[]
    })
    let param = {
      //isAuth: true,
      className: 'user',
      data: {
        depart: paramObj.id,
        searchAll: true,
        selectFields: ['id','userName','personalPhone','nickName']
      }
    }

    //模糊查询
    let complex = [{
      or: {
        userName: '%' +this.data.searchValue+ '%',
        nickName: '%' +this.data.searchValue+ '%'
      }
    }];
    param.data.complex = complex;
    CommonService.goFindList(param).then(res=>{
      console.log(res);
      if (res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
       
      
        console.log(map);
        // this.data.editInfo.cleanOrderUsers.forEach(item => {
          
        // });
        let userList=[];
        result.forEach(item3 => {
            userList.push({
              id: item3.id,
              userName: item3.userName,
              nickName:  item3.nickName,
              personalPhone: item3.personalPhone
            });
        });
        let map=new Map();
        if(this.data.editInfo && this.data.editInfo.taskApproveList){
          this.data.editInfo.taskApproveList.forEach(item =>{
            map.set(item.id,item);
          })
          //选中状态
        userList.forEach(item => {
          if(map.get(item.id)){
            item.checked=true;
          }
        });
        }
        

        this.setData({
          taskApproveList: userList
        })
      }
    }).catch((error) => {
    })
  },

  //显示脱岗提醒人员多选框
  onShowUser(){
    this.setData({
      showUser: true
    })

    //查询人员
    this.getBindUser();
  },

  //隐藏脱岗提醒人员多选框
  onCloseUser(){
    this.setData({
      showUser: false,
      searchValue: ''
    })
  },

  //隐藏物业工单接收人多选框
  onCloseCleanOrderUser(){
    this.setData({
      showSelect: false,
      searchCleanOrderValue: ''
    })
  },

  //隐藏任务审批人
  onCloseTaskApprove(){
    this.setData({
      showTaskApprove: false,
    })
  },

  //查询脱岗提醒人员
  getBindUser(){
    this.setData({
      userList: []
    })

    let param = {
      //isAuth: true,
      className: 'user',
      data: {
       // depart: this.data.paramObj.companyId,
        searchAll: true,
        selectFields: ['id','userName','personalPhone','nickName']
      }
    }

    //模糊查询
    let complex = [{
      or: {
        userName: '%' +this.data.searchValue+ '%',
        nickName: '%' +this.data.searchValue+ '%'
      }
    }];
    param.data.complex = complex;

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let ids=[];
        result.forEach(item => {
          ids.push(item.id);
        });

        //查询绑定微信的人员
        let param2={
          isAuth: false,
          className:'wechatLogin',
          data:{
            userId: ids,
            selectFields: ['id','userId','gzhopenid'],
            nbl: Base64.encode(util.timeFormatDay(new Date())),
            searchAll: true,
          }
        }

        CommonService.goFindList(param2).then(res=>{
          if (res.data.data && res.data.data.result && res.data.data.result.length) {
            let result2=res.data.data.result;
            let map=new Map();

            result2.forEach(item2 => {
              //有gzhopenid的才能选
              if(item2.gzhopenid){
                map.set(item2.userId,item2);
              }
            });

            let userList=[];
            result.forEach(item3 => {
              if(map.has(item3.id)){
                userList.push({
                  userId: item3.id,
                  userName: item3.userName,
                  openId: map.get(item3.id).gzhopenid,
                  nickName:  item3.nickName,
                  personalPhone: item3.personalPhone
                });
              }
            });

            //选中状态
            let listMap=this.data.listMap;
            userList.forEach(item => {
              if(listMap.get(item.userId)){
                item.checked=true;
              }
            });

            this.setData({
              userList: userList
            })
          }
        }).catch((error) => {
        })

      }
    }).catch((error) => {
    })
  },

  //全选
  onChangeAll(event){
    let list=this.data.userList;
    let listMap=this.data.listMap;

    list.forEach(item => {
      //列表的复选框与全选的值一致
      item.checked=event.detail;
      if(event.detail){
        //选中的放入已选列表
        listMap.set(item.userId,item);
      }else{
        //未选中的从map中删除
        listMap.delete(item.userId);
      }
    });

    this.setData({
      checkedAll: event.detail,
      userList: list,
      listMap: listMap
    })
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.trim()
    })
    this.getBindUser();
  },

  //选择列表
  onChangeCheck({currentTarget}) {
    let detail=currentTarget.dataset.detail;
    let list=this.data.userList;
    let listMap=this.data.listMap;
    console.log(listMap);
    list.forEach(item => {
		  if(item.userId==detail.userId){
        //点击复选框时切换选中
        item.checked=!item.checked;
        if(item.checked){
          //选中的放入已选列表，利用map避免重复
          listMap.set(item.userId,item);
        }else{
          //未选中的从map中删除
          listMap.delete(item.userId);
        }
      }
    });

    //列表是否全被选中了
    let flag=list.every(item=>{
      return item.checked;
    });

    //是否选中全选
    if(flag){
      this.setData({
        checkedAll: true
      })
    }else{
      this.setData({
        checkedAll: false
      })
    }

    this.setData({
      userList: list,
      listMap: listMap
    })
  },

  //选择任务审批人
  onChangeTaskApprover({currentTarget}){
    let detail=currentTarget.dataset.detail;
    let list=this.data.taskApproveList;
    let listMap=this.data.listTaskApproverMap;
    console.log(detail);
    console.log(list);
    console.log(listMap);
    
    list.forEach(item => {
		  if(item.id==detail.id){
        //点击复选框时切换选中
        item.checked=!item.checked;
        if(item.checked){
          //选中的放入已选列表，利用map避免重复
          listMap.set(item.id,item);
        }else{
          //未选中的从map中删除
          listMap.delete(item.id);
        }
      }
    });
    //列表是否全被选中了
    let flag=list.every(item=>{
      return item.checked;
    });

    //是否选中全选
    if(flag){
      this.setData({
        checkedAll: true
      })
    }else{
      this.setData({
        checkedAll: false
      })
    }

    this.setData({
      taskApproveList: list,
      listTaskApproverMap: listMap
    })

    console.log(this.data);
    
  },


  //选择列表
  onChangeCleanOrderCheck({currentTarget}) {
    let detail=currentTarget.dataset.detail;
    let list=this.data.selectList;
    let listMap=this.data.listCleanOrderMap;
    console.log(detail);
    console.log(list);
    console.log(listMap);
    list.forEach(item => {
		  if(item.id==detail.id){
        //点击复选框时切换选中
        item.checked=!item.checked;
        if(item.checked){
          //选中的放入已选列表，利用map避免重复
          listMap.set(item.id,item);
        }else{
          //未选中的从map中删除
          listMap.delete(item.id);
        }
      }
    });

    //列表是否全被选中了
    let flag=list.every(item=>{
      return item.checked;
    });

    //是否选中全选
    if(flag){
      this.setData({
        checkedAll: true
      })
    }else{
      this.setData({
        checkedAll: false
      })
    }

    this.setData({
      selectList: list,
      listCleanOrderMap: listMap
    })
  },


  //确定人员
  onConfirmUser(){
    let listMap=this.data.listMap;
    //map转成数组
    let arr=[...listMap.values()];

    //名字
    let names=[];
    arr.forEach(item => {
		  names.push(item.nickName);
		});

    let offMessageUsers='editInfo.offMessageUsers';
    let self_offMessageUsers='editInfo.self_offMessageUsers';

    this.setData({
      [offMessageUsers]: arr,
      [self_offMessageUsers]: names
    })

    this.onCloseUser();
  },

  //确定
  onConfirmTaskApprover(){
    let listMap=this.data.listTaskApproverMap;
    //map转成数组
    let arr=[...listMap.values()];

    //名字
    let names=[];
    arr.forEach(item => {
		  names.push(item.nickName);
		});

    let taskApprover='editInfo.taskApproveList';
    let self_taskApprover='editInfo.self_taskApprover';

    this.setData({
      [taskApprover]: arr,
      [self_taskApprover]: names
    })

    this.onCloseTaskApprove();
    console.log(this.data);
  },


  //确定人员
  onConfirmCleanOrderUser(){
    let listMap=this.data.listCleanOrderMap;
    //map转成数组
    let arr=[...listMap.values()];

    //名字
    let names=[];
    arr.forEach(item => {
		  names.push(item.name);
		});

    let offMessageUsers='editInfo.cleanOrderUsers';
    let self_offMessageUsers='editInfo.self_cleanOrderUsers';

    this.setData({
      [offMessageUsers]: arr,
      [self_offMessageUsers]: names
    })

    this.onCloseCleanOrderUser();
  },


  //将提醒相关信息保存到工牌表
  updateCardReceiver(obj){
    CommonService.updateCardReceiver(obj).then(res=>{
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
